package org.example.factory.support;

import org.example.exception.BeansException;
import org.example.factory.DisposableBean;
import org.example.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author: luyg
 * @Date: 2024/09/05/23:56
 * @Description:
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {
    protected static final Object NULL_OBJECT = new Object();

    private final Map<String,Object> singletonObjects=new HashMap<>();

    private final Map<String, DisposableBean> disposableBeans=new HashMap<>();

    @Override
    public Object getSingleton(String beanName) {
        return singletonObjects.get(beanName);
    }



    protected void addSingleton(String beanName,Object singletonObject){
        singletonObjects.put(beanName,singletonObject);
    }

    protected void registerDisposableBean(String beanName,DisposableBean disposableBean){
        disposableBeans.put(beanName,disposableBean);
    }

    @Override
    public void destroySingletons() {
        Set<String> strings = this.disposableBeans.keySet();
        Object[] array = strings.toArray();
        for (int i = 0; i < array.length; i++) {
            Object beanName = array[i];
            DisposableBean disposableBean = disposableBeans.remove(beanName);
            try {
                disposableBean.destroy();
            } catch (Exception e) {
                throw new BeansException("Destroy method on bean with name '" + beanName + "' threw an exception", e);
            }
        }
    }

    @Override
    public void registerSingleton(String beanName, Object singletonObject) {
        singletonObjects.put(beanName, singletonObject);
    }
}
